package cn.smart.epic.core.shiro.check;

import cn.smart.epic.core.listener.ConfigListener;
import cn.smart.epic.core.shiro.ShiroKit;
import cn.smart.epic.core.shiro.ShiroUser;
import cn.smart.epic.core.support.HttpKit;
import cn.smart.epic.core.util.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther Z.B
 * @date 2017/10/11 17:28
 * @Email 2545375@qq.com
 * @Description 请输入你的描述
 * @since 1.0
 */

@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class PermissionCheckFactory implements ICheck {

    public static ICheck me() {
        return SpringContextHolder.getBean(ICheck.class);
    }

    @Override
    public boolean check(Object[] permissions) {
        ShiroUser user = ShiroKit.getShiroUser();
        if (user == null) {
            return false;
        }
        String join = StringUtils.join(permissions, ",");
        if (ShiroKit.hasAnyRoles(join)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean checkAll() {
        HttpServletRequest request = HttpKit.getRequest();
        ShiroUser user = ShiroKit.getShiroUser();
        if (user == null) {
            return false;
        }
        String requestURI = request.getRequestURI().replace(ConfigListener.getConf().get("contextPath"), "");
        String str[] = requestURI.split("/");
        if (str.length > 3) {
            requestURI = "/" + str[1] + "/" + str[2];
        }

        if (ShiroKit.hasPermission(requestURI)) {
            return true;
        }
        return false;
    }
}
